package com.jie.netty.im.tactics.impl;

import com.jie.constants.ChannelAttrKey;
import com.jie.constants.IMRedisKey;
import com.jie.netty.im.tactics.DisconnectionHandler;
import com.jie.utils.SpringContextHolder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 登录信息的断开处理类
 */
@Slf4j
public class LoginDisconnectionHandler implements DisconnectionHandler {

    @Override
    public void handleDisconnection(ChannelHandlerContext ctx) {
        AttributeKey<String> userIdAttr = AttributeKey.valueOf(ChannelAttrKey.USER_NAME);
        String username = ctx.channel().attr(userIdAttr).get();
        AttributeKey<Integer> terminalAttr = AttributeKey.valueOf(ChannelAttrKey.TERMINAL_TYPE);
        Integer terminal = ctx.channel().attr(terminalAttr).get();
        RedisTemplate<String, Object> redisTemplate = SpringContextHolder.getBean("redisTemplate");
        String key = String.join(":", IMRedisKey.IM_USER_SERVER_ID, username, terminal.toString());
        log.info("im连接断开,userName:{},终端类型:{}", username, terminal);
        redisTemplate.delete(key);
    }
}